﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using YougeBookmark.Models;
using YougeBookmark.Services;
using YougeBookmark.Utilities;

namespace YougeBookmark.Views
{
    /// <summary>
    /// 高级查询窗体（支持多条件分页查询）
    /// </summary>
    public partial class QueryForm : Form
    {
        private readonly DatabaseService _dbService;
        private readonly PaginationHelper _pager = new PaginationHelper();
        private List<Tag> _allTags = new List<Tag>();

        // UI控件
        private CheckedListBox chkTags;
        private DateTimePicker dtpStart;
        private DateTimePicker dtpEnd;
        private DataGridView dgvResults;
        private Button btnQuery;
        private Button btnPrev;
        private Button btnNext;
        private Label lblPageInfo;

        public QueryForm(DatabaseService dbService)
        {
            _dbService = dbService;
            InitializeComponent();
            Load += QueryForm_Load;
        }

        /// <summary>
        /// 初始化窗体控件（手动布局）
        /// </summary>
        private void InitializeComponent()
        {
            // 窗体设置
            Text = "高级查询";
            Size = new Size(900, 600);
            StartPosition = FormStartPosition.CenterParent;
            Font = new Font("微软雅黑", 9F);

            // 标签选择区
            var lblTags = new Label
            {
                Text = "选择标签:",
                Location = new Point(20, 20),
                AutoSize = true
            };
            chkTags = new CheckedListBox
            {
                Location = new Point(20, 50),
                Width = 200,
                Height = 200,
                CheckOnClick = true,
                MultiColumn = true,
                SelectionMode = SelectionMode.MultiExtended
            };

            // 时间范围选择区
            var lblDate = new Label
            {
                Text = "时间范围:",
                Location = new Point(240, 20),
                AutoSize = true
            };
            dtpStart = new DateTimePicker
            {
                Location = new Point(240, 50),
                Width = 200,
                CustomFormat = "yyyy-MM-dd HH:mm",
                Format = DateTimePickerFormat.Custom
            };
            var lblTo = new Label
            {
                Text = "至",
                Location = new Point(450, 50),
                AutoSize = true
            };
            dtpEnd = new DateTimePicker
            {
                Location = new Point(480, 50),
                Width = 200,
                CustomFormat = "yyyy-MM-dd HH:mm",
                Format = DateTimePickerFormat.Custom
            };

            // 分页控件
            btnPrev = new Button
            {
                Text = "上一页",
                Location = new Point(240, 90),
                Width = 80,
                Enabled = false
            };
            btnPrev.Click += BtnPrev_Click;

            lblPageInfo = new Label
            {
                Text = "第0页/共0页",
                Location = new Point(330, 95),
                AutoSize = true
            };

            btnNext = new Button
            {
                Text = "下一页",
                Location = new Point(480, 90),
                Width = 80,
                Enabled = false
            };
            btnNext.Click += BtnNext_Click;

            // 查询按钮
            btnQuery = new Button
            {
                Text = "查询",
                Location = new Point(700, 50),
                Width = 80,
                BackColor = Color.LightBlue
            };
            btnQuery.Click += BtnQuery_Click;

            // 结果展示区
            dgvResults = new DataGridView
            {
                Location = new Point(20, 150),
                Width = 840,
                Height = 400,
                Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom,
                ReadOnly = true,
                RowHeadersVisible = false,
                AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill,
                BackgroundColor = Color.WhiteSmoke
            };
            dgvResults.Columns.Add("Tags", "关联标签");
            dgvResults.Columns.Add("Url", "URL地址");
            dgvResults.Columns.Add("Remark", "用户备注");
            dgvResults.Columns.Add("CreatedTime", "创建时间");

            // 添加所有控件
            Controls.AddRange(new Control[] {
                lblTags, chkTags,
                lblDate, dtpStart, lblTo, dtpEnd,
                btnPrev, lblPageInfo, btnNext,
                btnQuery,
                dgvResults
            });
        }

        /// <summary>
        /// 窗体加载初始化数据
        /// </summary>
        private async void QueryForm_Load(object sender, EventArgs e)
        {
            try
            {
                // 设置默认时间范围（最近一周）
                dtpStart.Value = DateTime.Now.AddDays(-7);
                dtpEnd.Value = DateTime.Now;

                // 加载所有标签
                _allTags = await _dbService.GetAllTagsAsync();
                chkTags.Items.Clear();
                foreach (var tag in _allTags)
                {
                    chkTags.Items.Add(tag.Name, false);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 执行查询并刷新界面
        /// </summary>
        private async void RefreshData()
        {
            try
            {
                // 设置查询条件
                _pager.SetDateRange(dtpStart.Value, dtpEnd.Value);

                var selectedTags = new List<int>();
                foreach (int index in chkTags.CheckedIndices)
                {
                    selectedTags.Add(_allTags[index].Id);
                }
                _pager.AddTags(selectedTags);

                // 执行分页查询
                var (data, total) = await _dbService.QueryBookmarksAsync(_pager);

                // 更新分页信息
                _pager.TotalCount = total;
                lblPageInfo.Text = $"第{_pager.CurrentPage}页/共{_pager.TotalPages}页";
                btnPrev.Enabled = _pager.CurrentPage > 1;
                btnNext.Enabled = _pager.CurrentPage < _pager.TotalPages;

                // 绑定数据
                dgvResults.Rows.Clear();
                foreach (var item in data)
                {
                    dgvResults.Rows.Add(
                        string.Join(", ", item.BookmarkTags.Select(bt => bt.Tag.Name)),
                        item.Url,
                        item.Remark,
                        item.CreatedTime.ToLocalTime()
                    );
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询失败: {ex.Message}");
            }
        }

        #region 事件处理
        /// <summary>
        /// 查询按钮点击事件
        /// </summary>
        private void BtnQuery_Click(object sender, EventArgs e)
        {
            _pager.CurrentPage = 1; // 重置到第一页
            RefreshData();
        }

        /// <summary>
        /// 上一页按钮点击事件
        /// </summary>
        private void BtnPrev_Click(object sender, EventArgs e)
        {
            if (_pager.CurrentPage > 1)
            {
                _pager.CurrentPage--;
                RefreshData();
            }
        }

        /// <summary>
        /// 下一页按钮点击事件
        /// </summary>
        private void BtnNext_Click(object sender, EventArgs e)
        {
            if (_pager.CurrentPage < _pager.TotalPages)
            {
                _pager.CurrentPage++;
                RefreshData();
            }
        }
        #endregion

        #region 辅助方法
        /// <summary>
        /// 打开时自动聚焦查询按钮（提升用户体验）
        /// </summary>
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            btnQuery.Focus();
        }

        /// <summary>
        /// 双击行打开URL（需处理异常）
        /// </summary>
        private void DgvResults_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;

            var url = dgvResults.Rows[e.RowIndex].Cells["Url"].Value?.ToString();
            if (!string.IsNullOrWhiteSpace(url))
            {
                try
                {
                    System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(url)
                    {
                        UseShellExecute = true
                    });
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"打开链接失败: {ex.Message}");
                }
            }
        }
        #endregion
    }
}